package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZJ
 */
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spu 表更新
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods", table = {"tb_spu"})   //代表监听那个数据库哪个表
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        System.err.println("tb_spu表数据发生变化");

        //获取修改前数据并转换为map
        HashMap<String, String> oldData = new HashMap<>();
        rowData.getBeforeColumnsList().forEach((c)->oldData.put(c.getName(),c.getValue()));

        //获取修改后数据并转换为map
        Map<String,String> newDate = new HashMap<>();
        rowData.getAfterColumnsList().forEach((c)->newDate.put(c.getName(),c.getValue()));

        //获取最新上架的商品,即从map中拿出对应上架的字段 进行比对 is_marketable
        if("0".equals(oldData.get("is_marketable")) && "1".equals(newDate.get("is_marketable"))){
            //没修改之前上架字段为0 上架之后 为1  条件成立 向交换机发送spuid
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newDate.get("id"));

        }

        //获取下架的商品,即从map中拿出对应上架的字段 进行比对 is_marketable
        if("1".equals(oldData.get("is_marketable")) && "0".equals(newDate.get("is_marketable"))){
            System.out.println("监控到tb_spu表变化（下架操作），发送到mq");
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newDate.get("id"));
        }

        //获取最新审核商品
       /* if ("0".equals(oldData.get("status")) && "1".equals(newDate.get("status"))){
            //发送商品spuId
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newDate.get("id"));
        }*/
    }
}
